<?php
namespace app\api\model;

use think\Model;
use think\Db;

class ClubModel extends Model
{
    function clublist(){
        $result=Db::name('club')->select();
        return $result;
    }
    function clubdetail($clubid) {
        $club =  db('club')->where('clubid', $clubid)->find();
        return $club;
    }

    function collect($userid, $clubid) {
        //判断用户存在
        $hasUser = Db::name('user')
            ->where('userid', $userid)
            ->select();

        if (!$hasUser) {
            return ['success' => -1, 'msg' => '无此用户'];
        }

        //判断活动
        $hasClub = Db::name('club')
            ->where('clubid', $clubid)
            ->select();

        if (!$hasClub) {
            return ['success' => -1, 'msg' => '无此活动'];
        }

        //是否已经收藏
        $isCollect = db('club_follow')
            ->where('clubid', $clubid)
            ->where('userid', $userid)
            ->find();

        if ($isCollect) {
            $res = db('club_follow')
                ->where('clubid', $clubid)
                ->where('userid', $userid)
                ->delete();
            if ($res) {
                return ['success' => 0, 'msg'=>'取消收藏'];
            } else {
                return ['success' => -1, 'msg'=>'取消收藏失败'];
            }
        } else {
            $data = ['userid' => $userid, 'clubid' => $clubid];
            $res = db('club_follow')->insert($data);
            if ($res) {
                return ['success' => 1, 'msg'=>'收藏成功'];
            } else {
                return ['success' => -1,'msg'=> '收藏失败'];
            }
        }
    }

    function isCollect($userid, $clubid) {
        $res = db('club_follow')
            ->where('clubid', $clubid)
            ->where('userid', $userid)
            ->find();
        if ($res) {
            return ['success' => 1];
        } else {
            return ['success' => 0];
        }
    }

    function getlesson($clubid) {
        $res = db('club_lesson')->select();
        return $res;
    }

    function collectClubList($userid){
        $res = Db::table('club_follow')
            ->alias('follow')
            ->join('club',"follow.clubid=club.clubid and follow.userid = '$userid'")
            ->select();
        return $res;
    }
}